import React from 'react'
import {Tooltip,Spin,Tree,Table, Card, Button, Form, Message, Row, Col, DatePicker,Modal,Input,Lable, Select,Popconfirm } from 'antd'
import {fetchPost} from './common/request'
import {treeDeal,treeRefTitleDeal} from './common/common.js'
import {errorNotify,successNotify,showLess} from './common/common'
import BusinessFilter from './common/BusinessFilter'

const TreeNode = Tree.TreeNode
const RangePicker = DatePicker.RangePicker
const Option = Select.Option

const FormItem = Form.Item

class MessageSearch extends React.Component {
  constructor (props) {
    super(props)
  }

  state = {
    TitleData: [],
    detailDate : [],

    loading: false,
    newModalVis : false,
    recordIsNew : false,
    detailInfoVis : false,

    // 列表
    appList: [],
    bizFuncList: [],
    servicerList: [],
    templateList: [],
    ruleList: [],

    selectedRows : null,
    selectedAppId : null,
    //记录
    record : {},
    detailItem :{},
    page: {
      currentPage: 1,
      pageSize: 10
    },
    loading:false,
  }

  componentWillMount() {
    this.getTitle()
    this.getAppList()
  }

  addBusiness(){
    fetchPost('/business/addBusinessTemplateInfo',this.state.record).then( json => {
      if (json.code != 200) {
        errorNotify('Add failure',json.msg)
      } else {
        successNotify('Add success')
        this.onReloadCache()
        this.state.record = {}
        if (this.state.selectedKeys)
          this.loadBusinessInfo(this.state.selectedKeys)
      }
    });
  }

  getTitle() {
    fetchPost('/business/getTitleList').then( json => {
      if (json.data != null) {
        var data = json.data
        treeRefTitleDeal(data)
        this.setState({
          TitleData: data
        });
      }
    });
  }

  //获取业务列表
  getBizFuncList(appId) {
    var param = null;
    if(appId) {
      param = {}
      param.appId = appId
    }
    fetchPost('/bizFunc/getBizFuncList',param).then( json => {
      if (json.data != null) {
        this.setState({
          bizFuncList: json.data
        });
      }
    });
  }

  getRuleList = (appId) => {
    var param = null;
    if(appId) {
      param = {}
      param.appId = appId
    }
    fetchPost('/rule/getRuleByAppId', param).then( json => {
      if (json.data != null) {
        this.setState({
          ruleList : json.data
        });
      }
    });
  }

  getTemplateList = (appId) => {
    var param = null;
    if(appId) {
      param = {}
      param.appId = appId
    }
    fetchPost('/template/getTemplateList',param).then( json => {
      if (json.data != null) {
        this.setState({
          templateList:json.data
        });
      }
    });
  }

  // 获取besinessRef
  getBusinessInfo(param) {
    this.setState({
      loading: true
    })
    fetchPost('/business/getAllBusinessTemplateInfo',param).then( json => {
      if (json.data != null) {
        let data = json.data
        let list = data.data

        for (var i=0; i < list.length; i++) {
          if(list[i].sendFlag === 0){
            list[i].sendFlag = "删除"
          } else {
            list[i].sendFlag = "正常"
          }
        }
        this.setState({
          loading: false,
          detailData:data.data,
          page : {
            currentPage : data.currentPage,
            totalCount: data.totalCount,
            pageSize: data.pageSize,
          },
        });
      } else {
        if (json.msg != null){
          errorNotify("Query failure",json.msg)
        }
        this.setState({
          loading: false,
          detailData:null,
        })
      }
    });
  }

  //分页下一页
  nextPage(current) {
    this.state.page.currentPage = current
    this.loadBusinessInfo(this.state.selectedKeys);
  }

  // tree选中后 加载businessRef，查询
  loadBusinessInfo = (selectedKeys,e,extra) => {
    // 如果选中2次，selected == false, 将之前保存的选中信息删除
    if (e && e.selected === false) {
      this.setState({
        selectedKeys : null,
        selectedAppId : null,
      })
      return
    }
    // 用于新增后刷新页面,直接使用state的selectKeys进行查询
    this.state.selectedKeys = selectedKeys;
    let param = {}
    let keys = selectedKeys[0].split("-")
    if(keys[1]){
      param.businessTypeId = keys[0]
      param.appId = keys[1]
      // 用于新增时直接添加app
      this.state.selectedAppId= parseInt(param.appId)
    }
    param.pageSize = this.state.page.pageSize;
    param.currentPage = this.state.page.currentPage

    this.getBusinessInfo(param)
  }

  // 过滤 查询 数据
  getSearchData = (selectedKeys,searchData) => {
    let param = {}
    // 如果selectKeys不存在，使用之前保存的selectedKeys
    if (selectedKeys) {
      //用于新增后刷新页面
      this.state.selectedKeys = selectedKeys
    }
    let keys = this.state.selectedKeys[0].split("-")
    if(keys[1]){
      param.businessTypeId = keys[0]
      param.appId = keys[1]
      // 用于新增时直接添加app
      this.state.selectedAppId= parseInt(param.appId)
    }

    // 遍历searchData的属性，赋值给param
    for (let prop in searchData) {
      param[prop] = searchData[prop];
    }
    param.pageSize = this.state.page.pageSize;
    param.currentPage = this.state.page.currentPage

    // 获取businessRef
    this.getBusinessInfo(param)
  }

  // 获取服务商列表
  getServicerList = (appId) => {
    let param = null
    if (appId) {
      param = {}
      param.appId = appId
      fetchPost('/servicer/getListByServicer',param).then( json => {
        if (json.data != null) {
          this.setState({
            servicerList : json.data
          });
        }
      });
    }
    else {

    }
    fetchPost('/servicer/getListByServicer',param?param:null).then( json => {
      if (json.data != null) {
        this.setState({
          servicerList : json.data
        });
      }
    });
  }

  getAppList() {
    fetchPost('/appInfo/getAppInfo').then( json => {
      if (json.data != null) {
        treeDeal(json.data)
        this.setState({
          appList: json.data
        });
      }
    });
  }

  // 新增和修改对话框的维护
  showNewModal = () => {
    this.getAppList()
    this.props.form.resetFields()
    this.getDefaultValue()

    if (this.state.selectedAppId){
      let value = this.state.selectedAppId
      this.state.record.appId = value
      this.state.appList.map(app => {
        var a = this.state.record
        if (app.appId == value){
          a.businessTypeId = app.businessTypeId
        }
        this.setState({
          record: a
        })
      })
      this.getTemplateList(value)
      this.getBizFuncList(value)
      this.getRuleList(value)
      this.getServicerList(value)
    }

    this.setState({
      newModalVis: true,
      recordIsNew: true,
    });

  }
  // 新增和修改对话框的维护
  showUpdateModal = (record) => {
    this.props.form.resetFields();
    this.state.record = record
    this.setState({
      record : record,
      newModalVis: true,
      recordIsNew: false,
    });
  }

  handleVisOk = (e) => {
    this.props.form.validateFields((err, values) => {
      if (!err) {
        // 判断是新增还是修改
        if (this.state.newModalVis)
          this.addBusiness()
        this.setState({
          newModalVis: false,
        })
      }
    });
  }
  handleVisCancel = (e) => {
    this.setState({
      newModalVis: false,
    });
  }

  detailInfoHide = (e) => {
    this.setState({
      detailInfoVis: false
    })
  }


  onReloadCache = () => {
    fetchPost('/business/reloadCache').then( json => {
      if (json.data != null) {
        treeDeal(json.data)
        this.setState({
          appList: json.data
        });
      }
      this.setState({
        loading: false
      })
    });
  }

  // 删除记录
  onDelete = (key) => {
  }

  appChange = (value, option) => {
    // 重置表单域
    this.state.record.appServicerId = null
    this.state.record.bizFunctionId = null
    this.state.record.messageTemplateId = null
    this.props.form.resetFields()

    this.state.record.appId = value
    this.state.appList.map(app => {
      var a = this.state.record
      if (app.appId == value){
        a.businessTypeId = app.businessTypeId
      }
      this.setState({
        record: a
      })
    })
    this.getTemplateList(value)
    this.getBizFuncList(value)
    this.getRuleList(value)
    this.getServicerList(value)
  }
  servicerChange = (value) => {
    this.state.record.appServicerId = value
  }
  templateChange = (value,option) => {
    for(var i=0,len=this.state.templateList.length; i< len; i++){
      if(this.state.templateList[i].msgTmpId === value){
        this.state.record.bizFunctionId = parseInt(this.state.templateList[i].bizId)
      }
    }
    // templateList
    // console.log(option)
    this.state.record.messageTemplateId = value
  }
  ruleChange = (value) => {
    this.state.record.sendRuleId = value
  }
  rankChange = (value) => {
    this.state.record.rank = value.target.value

  }

  getDefaultValue = () => {
    let a = this.state.record;
    a.rank = 1
    this.setState({
      record: a
    })
    this.props.form.setFieldsValue({'rank':this.state.record.rank})
  }

  // 加载树形控件
  onLoadTreeData = (treeNode) => {
    return new Promise((resolve) => {
      if (treeNode.props.children || treeNode.props.appInfoVoList) {
        resolve();
        return;
      }
    });
  }

  renderTreeNodes = (data) => {
    return data.map((item) => {
      if (item.children || item.appInfoVoList) {
        return (
          <TreeNode title={item.title} key={item.key} dataRef={item}>
            {this.renderTreeNodes(item.children?item.children : item.appInfoVoList)}
          </TreeNode>
        );
      }
      return <TreeNode {...item} dataRef={item} />;
    });
  }

  enterIconLoading = () => {
    this.setState({ loading: true });
  }

  enterIconCanceling =() => {
    this.setState({ loading: false });
  }

  render() {
    let self = this
    const pagination = {
      total: this.state.page.totalCount,
      pageSize: this.state.page.pageSize,
      showSizeChanger: false,
      showQuickJumper: true,
      showTotal (total) {
        return `Total ${total} `
      },
      onChange (current){
        self.nextPage(current)
      }
    }
    const appOptions = this.state.appList.map(d => <Option value={d.appId}>{d.appName}</Option>);
    const templateOptions = this.state.templateList.map(d => <Option value={d.msgTmpId}>{d.bizName}:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{d.content}</Option>);
    const ruleOptions = this.state.ruleList.map(d => <Option value={d.ruleId}>{d.sendRuleName}</Option>);
    const servicerOptions = this.state.servicerList? this.state.servicerList.map(d => <Option value={d.asRefId}>{d.channelName}</Option>) : null;
    const { getFieldDecorator } = this.props.form;
    // 表单布局
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 },
      },
    };
    // 详情布局
    const detailItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 },
      },
    };
    // table 标题
    const columns = [{
      title: 'App name',
      dataIndex: 'appName',
      width : 80,
      key: 'appName',
      // render: text => <a href="#">{text}</a>,
    }, {
      title: 'Scenes',
      dataIndex: 'bizFunctionDesc',
      key: 'bizFunctionDesc',
      width : 140,
    }, {
      title: 'Channel Name',
      dataIndex: 'channelName',
      key: 'channelName',
      width : 100,
    },{
      title: 'Message Template',
      dataIndex: 'messageTemplateDesc',
      key: 'messageTemplateDesc',
      width : 300,
      render: (text, record) => {
        return showLess(text,record,300)
      }
    },{
      title: 'Send Rule ID',
      dataIndex: 'sendRuleId',
      key: 'sendRuleId',
    }, {
      title: 'Status',
      dataIndex: 'sendFlag',
      key: 'sendFlag',
    }, {
        title: 'Operate',
        dataIndex: 'action',
        key: 'action',
        width: 100,
        render: (text, record) => {
          const {editable} = record;
          return (
            <div>
              <Button onClick={() => {
                console.log(record)
                this.setState({detailInfoVis :true,detailItem:record})}}>
                Show details
              </Button>
              {/*<Button onClick={this.showUpdateModal.bind(this,record)}>
                  修改
              </Button>
              <Popconfirm title="确定删除该条数据?" onConfirm={() => this.onDelete(record.key)}>
                <Button>
                  删除
                </Button>
              </Popconfirm>*/}
            </div>
          );
        }
      }
    ];

    return(
      <Card>
        <Row>
          <Col span={4}>
            <Tree loadData={this.onLoadTreeData} onSelect={this.loadBusinessInfo} treeDefaultExpandAll={true}>
              {this.renderTreeNodes(this.state.TitleData)}
            </Tree>
          </Col>
          <Col span={20}>
            <BusinessFilter ref="filter" appId={this.state.selectedAppId} getSearchData={this.getSearchData}/>
            <Spin spinning={this.state.loading} delay={500}>
              <Table ref="table" wrappedComponentRef={(inst) => this.formRef = inst} dataSource={this.state.detailData} style={{position:'relative'}} columns={columns}
                     rowKey="businessRefId" pagination={pagination}
                     footer={() =>
                       <div>
                         <Button onClick={this.showNewModal.bind(this)}>New configuration</Button>
                         <Popconfirm title="Confirm reload configuration data?" onConfirm={() => this.onReloadCache()} onCancel={this.enterIconCanceling}>
                           <Button type="danger" loading={this.state.loading} onClick={this.enterIconLoading}>
                             Reload configuration
                           </Button>
                         </Popconfirm>
                       </div>
                     }>
              </Table>
            </Spin>
          </Col>
        </Row>

        <Modal ref="modal"
               title={this.state.recordIsNew ? "New":"Modify"}
               visible={this.state.newModalVis}
               onOk={this.handleVisOk}
               onCancel={this.handleVisCancel}
        >
          <Form>
            <FormItem {...formItemLayout} label = "app name">

              {getFieldDecorator('appId', {
                initialValue : this.state.record? this.state.record.appId || null : null,
                rules: [
                  { required: true, message: 'Please select app name!' },
                ],
              })(
                <Select placeholder="Please" onSelect={this.appChange}>
                  {appOptions}
                </Select>
              )}
            </FormItem>

            <FormItem {...formItemLayout} label = "Service Provider Channel">

              {getFieldDecorator('appServicerId', {
                initialValue : this.state.record? this.state.record.appServicerId || "" : "",
                rules: [
                  { required: true, message: 'Please select service provider channel!' },
                ],
              })(
                <Select placeholder="Service Provider Channel" onSelect={this.servicerChange}>
                  {servicerOptions}
                </Select>
              )}
            </FormItem>

            <FormItem {...formItemLayout} label = "Message template">

              {getFieldDecorator('template', {
                initialValue : this.state.record? this.state.record.template || "" : "",
                rules: [
                  { required: true, message: 'Please enter the message template！' },
                ],
              })(
                <Select placeholder="Message template" onSelect={this.templateChange}>
                  {templateOptions}
                </Select>
              )}
            </FormItem>

            <FormItem {...formItemLayout} label = "Priority" extra="Please fill in the priority, the default is 1, the smaller the value, the higher the priority!">
              {getFieldDecorator('rank', {
                initialValue : this.state.record? this.state.record.rank || "1" : "1",
                rules: [
                  { required: true, message: 'Please fill in the priority！' },
                ],
              })(
                <Col>
                  <Input placeholder="Please fill in the priority" onChange={this.rankChange} defaultValue="1" />
                  {/*<Tooltip title="请填写优先级，默认为1，值越小，优先级越高!">*/}
                    {/*<span>优先级排序</span>*/}
                  {/*</Tooltip>*/}
                </Col>
              )}
            </FormItem>

            <FormItem {...formItemLayout} label = "Send rule">
              {getFieldDecorator('rule', {
                initialValue :  null,
                rules: [],
              })(
                <Select placeholder="Send rule" onSelect={this.ruleChange}>
                  <Option value={null}>Send</Option>
                  {ruleOptions}
                </Select>
              )}
            </FormItem>

          </Form>
        </Modal>


        <Modal visible={this.state.detailInfoVis}
               title="Details" footer={null}
               onCancel={this.detailInfoHide}
        >
          <Form>
            <FormItem {...detailItemLayout} label = "app name">
              <Input readOnly={true} value={this.state.detailItem.appName}/>
            </FormItem>
            <FormItem {...detailItemLayout} label = "Scenes">
              <Input readOnly={true} value={this.state.detailItem.bizFunctionDesc}/>
            </FormItem>
            <FormItem {...detailItemLayout} label = "Service Name">
              <Input readOnly={true} value={this.state.detailItem.serviceName}/>
            </FormItem>
            <FormItem {...detailItemLayout} label = "Channel Name">
              <Input readOnly={true} value={this.state.detailItem.channelName}/>
            </FormItem>
            <FormItem {...detailItemLayout} label = "Template">
              <Input readOnly={true} value={this.state.detailItem.messageTemplateDesc}/>
            </FormItem>
            <FormItem {...detailItemLayout} label = "SMS Type">
              <Input readOnly={true} value={this.state.detailItem.msgType}/>
            </FormItem>
            <FormItem {...detailItemLayout} label = "Signature">
              <Input readOnly={true} value={this.state.detailItem.sign}/>
            </FormItem>
            <FormItem {...detailItemLayout} label = "Priority">
              <Input readOnly={true} value={this.state.detailItem.rank}/>
            </FormItem>
            <FormItem {...detailItemLayout} label = "Category Status">
              <Input readOnly={true} value={this.state.detailItem.sendFlag}/>
            </FormItem>
            <FormItem {...detailItemLayout} label = "Last Update Time">
              <Input readOnly={true} value={this.state.detailItem.lastUpdateTime}/>
            </FormItem>
          </Form>
        </Modal>
      </Card>
    );
  }
}

MessageSearch = Form.create()(MessageSearch)
export default MessageSearch


